// 文本输入框组件
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_deer/util/toast_utils.dart';

class TextInputWidget extends StatefulWidget {
  final bool obscureText; // 是否隐藏密码
  final Function(String)? onSubmitted; // 提交时的回调
  final Function(String)? onChanged; // 文本变化时的回调

  const TextInputWidget({
    super.key,
    this.obscureText = false,
    this.onSubmitted,
    this.onChanged,
  });

  @override
  State<TextInputWidget> createState() => _TextInputWidgetState();
}

class _TextInputWidgetState extends State<TextInputWidget> {
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    // 监听文本变化
    _controller.addListener(_onTextChanged);
  }

  @override
  void dispose() {
    _controller.removeListener(_onTextChanged);
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  void _onTextChanged() {
    // 文本变化时触发回调
    widget.onChanged?.call(_controller.text);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 文本输入区域
        Container(
          height: 40,
          width: 240,
          // decoration: BoxDecoration(
          //   color: Colors.white,
          //   borderRadius: BorderRadius.circular(4),
          //   border: Border.all(color: Colors.grey.shade300),
          // ),
          child: TextField(
            controller: _controller,
            focusNode: _focusNode,
            obscureText: widget.obscureText,
            // 控制是否隐藏文本
            maxLength: 6,
            // 限制最大长度为6
            keyboardType: TextInputType.number,
            inputFormatters: [
              FilteringTextInputFormatter.digitsOnly,
            ],
            textAlign: TextAlign.center,
            style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, letterSpacing: 5),

            //文本居中
            // textAlignVertical: TextAlignVertical.top,
            decoration: const InputDecoration(
              counterText: '', // 隐藏字符计数器
              border: const OutlineInputBorder(),
              contentPadding: EdgeInsets.symmetric(vertical: 0),
              hintText: '请输入6位数字密码',
            ),
            onSubmitted: (value) {
              // 点击回车时触发回调
              if (value.length == 6) {
                widget.onSubmitted?.call(value);
              } else {
                Toast.show('请输入6位数字密码');
              }
            },
          ),
        ),
      ],
    );
  }
}
